#!/usr/bin/python
#-*- coding: utf-8 -*-

###########################################################
# Copyright 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Kitchen of Awesome.
#
# Kitchen of Awesome is free software: you can redistribute it and/or 
# modify it under the terms of the GNU General Public License 
# as published by the Free Software Foundation, either 
# version 3 of the License, or (at your option) any later 
# version.
#
# Kitchen of Awesome is distributed in the hope that it will be 
# useful, but WITHOUT ANY WARRANTY; without even the implied 
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
# PURPOSE. See the GNU General Public License for more details.
#
# You should have hreceived a copy of the GNU General Public 
# License along with Kitchen of Awesome. 
# If not, see http://www.gnu.org/licenses/.
###########################################################

from data import KoaObject, APPLICATION
from random import random

"""
The class UserSkill represents the skill level of a specific
user in a specific skill
"""
class UserSkill(KoaObject):
    """
    This classmethod fetches all UserSkills related to a given 
    user-object from the Database
    """
    @classmethod
    def getUserSkills(cls, user):
        skills = APPLICATION.getStorage().find({'user_id':user.id, '_className':'UserSkill'})
        return [KoaObject.load(i['_id']) for i in skills]

    """
    This classmethod delivers a specific userskill determined by
    a given user-object and a given skill-object 
    """
    @classmethod
    def getUserSkill(cls,user,skill):
        skill = APPLICATION.getStorage().find({'user_id':user.id, 'skill_id':skill.id, '_className':'UserSkill'})
        return KoaObject.load(skill[0]) # HERE BE DRAGONS

    """
    This classmethod creates a new Userskill, stores it in the 
    database and returns it to the caller
    """
    @classmethod
    def createUserSkill(cls,user,skill):
        userSkill = UserSkill()
        userSkill.setUser(user)
        userSkill.setSkill(skill)
        userSkill.store()
        return userSkill

    """
    Constructor of UserSkill.
    Sets the defaultvalues
    0 as Startlevel
    """
    def __init__(self):
        KoaObject.__init__(self)
        self.skill = None
        self.user = None
        self.level = ""

    """
    setUser sets the user-object of this UserSkill instance
    """
    def setUser(self,user):
        if user.__class__.__name__ != "User":
            raise Exception ("Must be User")
        self.user = user

    """
    Returns the user-object of this UserSkill instance
    """
    def getUser(self):
        return self.user

    """
    setSkill sets the skill-object of this UserSkill instance
    """
    def setSkill(self,skill):
        if skill.__class__.__name__ != "Skill":
            raise Exception ("Must be Skill")
        self.skill = skill

    """
    Returns the skillobject of the current skilled user-object
    """
    def getSkill(self):
        return self.skill

    """
    Inrements the Level of this UserSkill by a value of 1 and a chance
    of p=0.75
    """
    def increaseLevel(self):
        if self.level+1 <= self.skill.getMaxlevel():
            if random() > 0.25:
                self.level+=1
                self.store()
    
    """
    Returns the Rank of this UserSkill.
    The Actual rank-strings are determined by this UserSkill's skill-object
    """
    def getRank(self):
        return self.skill.getRankForLevel(self.level)


KoaObject.registerClass(UserSkill)

"""
A Skill is something like "doin the dishes" or "wash clothes" or anything like that,
that represents unpleasant work in the koa-directed household and is to be rewarded
with skillpoints :)
"""
class Skill(KoaObject):
    """
    Returns every Skill in the current Koa-Database
    """
    @classmethod
    def getSkills(cls):
        skills = APPLICATION.getStorage().find({'_className':'Skill'})
        return [KoaObject.load(i['_id']) for i in skills]

    """
    Nevermind me
    """
    @classmethod
    def getSkillsForUser(cls,user):
        userskills = APPLICATION.getStorage().find({'user_id':user.id, '_className':'UserSkill'})
        return [KoaObject.load(i['_id']) for i in userskills]

    """
    Creates a new Skill and returns it to the caller
    name = the name of the new skill
    maxlevel = the maximum level that can be achieved by leveling this skill
    ranks = define own rank-definitions as dictionary
    """
    @classmethod
    def createSkill(cls, name, maxlevel, ranks=None):
        skill = Skill()
        skill.setName(name)
        skill.setMaxlevel(maxlevel)
        if ranks is not None:
            skill.setRanks(ranks)
        skill.store()
        return skill

    """
    Skill-Constructor
    merely sets default values
    """
    def __init__(self):
        KoaObject.__init__(self)
        self.name = ""
        self.maxlevel = 0
        self.ranks = {0:"Vollnoob",
                     75:"Anfaenger",
                    150:"Furchtloser Recke",
                    300:"Skiller",
                    450:"Pro"}

    """
    setRanks allows the user to generate custom ranks for this skill
    a skilllist should look something like this
    {0:"lowestrankname", .... , n : "somerankname in between", ... , n+m : "highestrank" }
    the keynumber is the lowest level necessary to have this rank
    """
    def setRanks(self,ranks):
        if type(ranks)!=dict:
            raise Exception("ranks must be dict")
        self.ranks = ranks

    """
    returns the rank for a specific level as rank-string
    """
    def getRankForLevel(self, level):
        level = int(level)
        indices = self.ranks.keys()
        indices.sort()
        for i in range(len(indices)):
            if level > indices[i]:
                continue
            else:
                return self.ranks[indices[i-1]]
        return self.ranks[indices[len(indices)-1]]

    """
    sets the name of this skillobject
    """
    def setName(self,name):
        self.name = name

    """
    returns the name of this skillobject 
    """
    def getName(self):
        return self.name

    """
    sets the maxlevel of this skillobject
    """
    def setMaxlevel(self,maxlevel):
        self.maxlevel = maxlevel

    """
    returns the maxlevel of this skillobject
    """
    def getMaxlevel(self):
        return self.maxlevel

KoaObject.registerClass(Skill)